package com.lmy.androidcustomview.view

import android.content.Context
import android.graphics.*
import android.os.Build
import android.os.Parcel
import android.os.Parcelable
import android.util.AttributeSet
import android.view.View
import androidx.annotation.RequiresApi
import com.lmy.androidcustomview.toPx
import java.nio.file.PathMatcher
import java.security.AccessControlContext
import java.util.jar.Attributes
import kotlin.math.cos
import kotlin.math.sin

/**
 * @author lmy
 * @功能: 仪表盘自定义View
 * @Creat 2/8/21 4:10 PM
 * @Compony 465008238@qq.com
 */

class DashboardView(context: Context?, attrs: AttributeSet)
    : View(context, attrs) {
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
    val RADIUS = 150f//半径
    val OPEN_ANGLE = 120f//下面开口角度
    val DASH_WIDTH = 2f.toPx//刻度的宽度
    val DASH_LENGTH = 5f.toPx//刻度的长度
    val dash = Path()//绘制刻度的Path
    val path = Path()//绘制实弧线的Path
    val LENGTH = 120f.toPx//指针的半径 也就是长度
    lateinit var pathEffect: PathEffect//Path的绘制效果

    init {
        paint.strokeWidth = 3f.toPx//设置线条宽度
        paint.style = Paint.Style.STROKE//设置划线模式 不填充
        dash.addRect(0f, 0f, DASH_WIDTH, DASH_LENGTH, Path.Direction.CCW)
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onDraw(canvas: Canvas) {
        //绘制实弧线
        canvas.drawPath(path, paint)
        //增加Path效果
        paint.pathEffect = pathEffect
        //绘制刻度弧线
        canvas.drawPath(path, paint)
        paint.pathEffect = null
        //画指针
        canvas.drawLine(
            width / 2f,
            height / 2f,
            (width / 2f + LENGTH * cos(MathToRadians())).toFloat(),
            (height / 2f + LENGTH * sin(MathToRadians())).toFloat(),
            paint
        )
    }

    private fun MathToRadians() =
        Math.toRadians((90 + OPEN_ANGLE / 2f + (360 - OPEN_ANGLE) / 20f * 10).toDouble())

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        path.reset()
        /**
         *开始坐标
         * 结束坐标
         * 开始角度
         * 旋转经过的角度
         * 是否连接开始结束封闭图形
         * 画笔
         */
        path.addArc(
            width / 2f - RADIUS.toPx,
            height / 2f - RADIUS.toPx,
            width / 2f + RADIUS.toPx,
            height / 2f + RADIUS.toPx,
            90 + OPEN_ANGLE / 2f,
            360 - OPEN_ANGLE
        )

        val pathMeasure = PathMeasure(path, false)
        /**
         * Path
         * advance 开始的位置
         * phase间隔距离   Android advance和phase是相反的
         * 拐角处的风格
         */
        pathEffect = PathDashPathEffect(
            dash,
            (pathMeasure.length - DASH_WIDTH) / 20f,
            0f,
            PathDashPathEffect.Style.ROTATE
        )
    }
}